﻿/// <reference path="../libs/jquery-1.8.2-vsdoc.js" />
var SCA = SCA || {};
SCA.UI = SCA.UI || {};
SCA.UI.Configuration = SCA.UI.Configuration || {};

SCA.UI.Configuration.Dialog = function () {

    this.CurrentIndex = -1;
    
    var currentContext = null;
    var currentWeb = null;
    var configList = null;
    var currentListItem = null;
    var currentConfiguration = null;

    this.Setup = function ()
    {
        jQuery("#ShowConfigurationURLButton").button().click(function () {
            jQuery("#ConfigurationURLDialog").dialog({ title: "Configuration URL", width: "400px" });
        });

        jQuery("#ConfigurationEditDialog").on("dialogclose", function (event, ui) { jQuery(".validity-modal-msg").hide(); });
        this.SetConfigurationURL();
        currentContext = new SP.ClientContext.get_current();
        currentWeb = currentContext.get_web();
        configList = currentWeb.get_lists().getByTitle("Configuration");
        
        
        jQuery("select[id$='DropDownListConfigurations']").change(function () {
            //the id is stored here to be visible from code behind
            //reason: changes to the dropdown from js do not affect the view state and thus the code behind is not aware of the new items
            jQuery("input[id$='HiddenFieldSelectedConfigurationUniqueIdClient']").val(GetDropDownListConfigurationSelectedValue());
        }
        );
    }

    this.New = function()
    {
        this.CurrentIndex = -1;
        GetInputTitle().val("");
        GetTextAreaDescription().val("");
    }

    this.Load = function()
    {
        var guid = GetDropDownListConfigurationSelectedValue();
        this.CurrentIndex = GetIndexForGuid(guid);
        var config = GetConfiguration(this.CurrentIndex);

        GetInputTitle().val(config.Title);
        GetTextAreaDescription().val(config.Description); 
    }


    this.Validate = function () {

        jQuery.validity.setup({ outputMode: "modal" });
        jQuery.validity.start();

        GetInputTitle().require("Required.");

        var result = jQuery.validity.end();
        return result.valid;
    }


    this.Save = function()
    {
        var isValid = this.Validate();
        if (!isValid)
            return;

        var index = this.CurrentIndex;
        var configuration;
        
        if (index == -1) //it's a new configuration
        {
            index = SCA.AllConfigurations.push({ }) - 1;

            var itemInfo = new SP.ListItemCreationInformation();
            currentListItem = configList.addItem(itemInfo);
            configuration = GetConfiguration(index);
        }
        else {
            configuration = GetConfiguration(index);
            currentListItem = configList.getItemById(configuration.ID);
        }


        configuration.Title = GetInputTitle().val();
        configuration.Description = GetTextAreaDescription().val();

        currentConfiguration = configuration;

        currentListItem.set_item('Title', configuration.Title );
        currentListItem.set_item('Description', configuration.Description);
        
        currentListItem.update();
        currentContext.load(currentListItem);
        currentContext.executeQueryAsync(Function.createDelegate(this, this.onSuccessfulItemUpdate), Function.createDelegate(this, this.onFailedItemUpdate));

        this.Close();
    }
    

    
    this.onSuccessfulItemUpdate = function (sender, args) {

        if (currentConfiguration.ID != null) {
            UpdateDropDownBox();
            return;
        }

        var targetListItem = configList.getItemById(currentListItem.get_id());
        currentContext.load(targetListItem, 'UniqueId');
        currentContext.executeQueryAsync(Function.createDelegate(this, function() {
            currentConfiguration.UniqueID = targetListItem.get_item("UniqueId").toString();
            currentConfiguration.ID = currentListItem.get_id();
            UpdateDropDownBox();
        }
        ), Function.createDelegate(this, function() { alert("failed") }));
    }
    

    var UpdateDropDownBox = function() {
       
        var found = false;
        jQuery("select[id$='DropDownListConfigurations'] > option").each(function() {
            if(this.value == currentConfiguration.UniqueID) {
                this.text = currentConfiguration.Title;
                found = true;
                return false; //to break from 'each'
            }
        });
        
        if(!found) {
            jQuery("<option value='"+currentConfiguration.UniqueID+"'>"+currentConfiguration.Title+"</option>").appendTo("select[id$='DropDownListConfigurations']");
        }
    }


    this.onFailedItemUpdate = function (sender, args) {
        alert("Error occured while saving the configuration.");
    }


    this.Close = function()
    {
        jQuery("#ConfigurationEditDialog").dialog("close");
    }


    this.SetConfigurationURL = function ()
    {
        var urlText = "Configuration URL: "+ location.href + "?ConfigId=" + GetDropDownListConfigurationSelectedValue();
        jQuery("#ConfigurationURLDialog").text(urlText);
    } 

    var GetIndexForGuid = function(guid)
    {
        for(var i = 0; i < SCA.AllConfigurations.length; i++)
        {
            var current = SCA.AllConfigurations[i];
            if (current.UniqueID === guid)
                return i;
        }
        return -1;
    }

    var GetConfiguration = function (index) {
        return SCA.AllConfigurations[index]; 
    }

    var GetInputTitle = function () {
        return jQuery("#InputConfigurationDialogTitle");
    }

    var GetTextAreaDescription = function () {
        return jQuery("#TextAreaConfigurationDialogDescription");
    }

    var GetDropDownListConfigurationSelectedValue = function()
    {
        return jQuery("select[id$='DropDownListConfigurations']").val();
    }

    var GetDropDownListConfigurationSelectedText = function()
    {
        return jQuery("select[id$='DropDownListConfigurations'] option:selected").text();
    }

    this.Setup();
};